package com.game.logic.fighting.skill.hurt;

import com.coment.cfg.luban.constant.AIDCFG;
import com.coment.game.fight.AttributeManagerLogic;
import com.coment.game.fight.Attrs;
import com.coment.message.HurtInfo;
import com.coment.po.roles.Roles;
import com.game.dao.user.roles.RolesDao;
import com.game.logic.fighting.attrs.FightingLogic;
import com.game.logic.fighting.formula.InjuryFormulaBase;
import com.game.logic.fighting.pve.FightingService;
import jakarta.annotation.Resource;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/// 伤害事件
@Slf4j
@Component
public class HurtInfoEventHandler {
    @Resource
    private RolesDao rolesDao;

    /// 进行了攻击
    @Getter
    @Setter
    @ToString
    public static class DoHurt extends ApplicationEvent {
        /// 攻击者
        public String rolesId;
        private final List<HurtInfo> hurtInfoList;
        public DoHurt(FightingService source, String rolesId, List<HurtInfo> hurtInfoList) {
            super(source);
            this.rolesId = rolesId;
            this.hurtInfoList = hurtInfoList;
        }
    }

    /// 进行了普通攻击
    @Async
    @EventListener(classes = HurtInfoEventHandler.DoHurt.class)
    public void doHurt(HurtInfoEventHandler.DoHurt event) {
        String rolesId = event.getRolesId();
        Roles roles = rolesDao.findByIdMust(rolesId);
        InjuryFormulaBase.DamageRegistration damageRegistration = InjuryFormulaBase.damageFrequencyRegistration.get(rolesId);
        if (damageRegistration == null) {
            return;
        }

        if (damageRegistration.cfg.hurtType == 2) {
            Map<Integer, Double> atkAttrs = roles.rolePanel.getAttribute();

            for (HurtInfo hurtInfo : event.getHurtInfoList()) {
                String targetId = hurtInfo.getRolesId();
                Roles target = rolesDao.findByIdMust(targetId);

                double addHurt = 0D;
                // 根据addByAtkAtt 获取额外伤害

                Attrs addByAtkAtt = AttributeManagerLogic.obtainAttrs(damageRegistration.cfg.attrBonusMarkup);
                for (Map.Entry<Integer, Double> entry : addByAtkAtt.entrySet()) {
                    Integer key = entry.getKey();
                    Double value = entry.getValue();
                    Double baseValue = atkAttrs.get(key);
                    addHurt += baseValue * value / 100;
                }

                FightingLogic.beHarmed(target, addHurt);

                hurtInfo.shield = target.rolePanel.getAttribute().get(AIDCFG.shield);
                log.debug("额外伤害: {}", addHurt);
                rolesDao.save(target);
            }
        }
    }
}
